<template>
  <div
    class="task"
    :showSearch="showSearch"
    :showAdd="showAdd"
    :req="reqFuns"
    :title="title"
    :tableLabelEx="tableLabelEx"
    :operateFormLabelEx="operateFormLabelEx"
    :operateRulesEx="operateRulesEx"
    :detailFormLabelEx="detailFormLabelEx"
    style="margin-top: 10px"
  >
    <!--添加表单-->
    <el-dialog ref="addDialog" :title="title+'/添加'" :visible.sync="isShow">
      <common-form
        ref="addForm"
        :form-label="operateFormLabel"
        :form="operateForm"
        :form-rules="operateRules"
        :inline="operateInline"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="confirm(reqFuns.addTask)">确 定</el-button>
      </div>
    </el-dialog>
    <!--搜索框和添加按钮-->
    <div class="search-header">
      <el-row>
        <el-col :span="20" style="margin-left: 10px">
          <SearchBox
            v-show="showSearch"
            :search-box-data="searchBoxData"
            :search-model="searchModel"
            @searchEvent="setSearchEvent"
          />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addTask" v-show="showAdd">+ 添加</el-button>
        </el-col>
      </el-row>
    </div>
    <!--搜索表格-->
    <el-dialog title="请选择航标" :visible.sync="searchResultVisible">
      <common-table
        :table-data="searchResultData"
        :table-label="searchResultLabel"
        :config="searchResultConfig"
        @sure="sure"
      />
    </el-dialog>
    <!--主页表格-->
    <common-table
      :table-data="tableData"
      :table-label="tableLabel"
      :config="config"
      @changePage="getList(reqFuns.getTasks)"
      @openDetail="openDetail"
      @del="delTask"
    />
    <!--右侧详情-->
    <el-drawer :title="title+'/详情'" :visible.sync="isDetailDrawerShow" :direction="drawerDirection">
      <el-scrollbar style="height: 800px" class="detail_scrollbar">
        <div>
          <common-form ref="detailForm" :form-label="detailFormLabel" :form="detailForm"/>
          <common-media-list :src-list="srcList"/>
        </div>
      </el-scrollbar>
    </el-drawer>
  </div>
</template>

<script>
import CommonForm from '../../components/CommonForm'
import CommonTable from '../../components/CommonTable'
import { getCurrentTime, isEmpty } from '@/utils/utils'
import SearchBox from '@/components/SearchBox'
import CommonMediaList from '@/components/CommonMediaList'

export default {
  components: {
    CommonMediaList,
    SearchBox,
    CommonForm,
    CommonTable
  },
  props: {
    showSearch: {
      type: Boolean,
      default: true
    },
    showAdd: Boolean,
    title: String,
    reqFuns: Object,
    tableLabelEx: Array,
    operateFormLabelEx: Array,
    operateRulesEx: Object,
    detailFormLabelEx: Array
  },
  data() {
    return {
      srcList: [],
      isDetailDrawerShow: false,
      searchResultVisible: false,
      drawerDirection: 'rtl',
      searchResultData: [],
      searchResultLabel: [
        {
          prop: 'AtoNName',
          label: '航标名称'
        },
        {
          prop: 'NavigationType',
          label: '航标类型'
        },
        {
          prop: 'ChannelName',
          label: '港口名称'
        },
        {
          prop: 'SeaRoute',
          label: '航道名称'
        }
      ],
      searchResultConfig: {
        loading: false,
        showCtl: true,
        showSure: true
      },
      searchModel: {
        // 搜索项的默认值可以放在这里，也可以添加自定义的其它参数,也可以将这一部分构建在searchBoxData中
      },
      searchBoxData: [
        { label: '航标类型', name: 'NavigationType', e: 'select', opts: [] },
        { label: '港口名称', name: 'ChannelName', e: 'select', opts: [] },
        { label: '航道名称', name: 'SeaRoute', e: 'select', opts: [] },
        { label: '航标名称', name: 'AtoNName', e: 'input' }
      ],
      operateInline: true,
      operateType: 'add',
      isShow: false,
      tableData: [],
      tableLabel: [
        {
          prop: 'Code',
          label: '任务编号'
        },
        {
          prop: 'AtoNName',
          label: '航标名称'
        },
        {
          prop: 'NavigationType',
          label: '航标类型'
        },
        {
          prop: 'ChannelName',
          label: '港口名称'
        },
        {
          prop: 'SeaRoute',
          label: '航道名称'
        },
        {
          prop: 'Location',
          label: '设置坐标'
        },
        {
          prop: 'Time',
          label: '完成时间'
        },
        {
          prop: 'Status',
          label: '任务状态'
        }
      ],
      config: {
        page: 1,
        total: 30,
        loading: false,
        showCtl: true
      },
      detailForm: {},
      detailFormLabel: [
        {
          model: 'Code',
          label: '编号',
          type: 'input',
          readOnly: true
        },
        {
          model: 'AtoNName',
          label: '航标名称',
          type: 'input',
          readOnly: true
        },
        {
          model: 'NavigationType',
          label: '航标类型',
          type: 'input',
          readOnly: true
        },
        {
          model: 'ChannelName',
          label: '港口名称',
          type: 'input',
          readOnly: true
        },
        {
          model: 'SeaRoute',
          label: '航道名称',
          type: 'input',
          readOnly: true
        },
        {
          model: 'PublishTime',
          label: '发布时间',
          type: 'input',
          readOnly: true
        },
        {
          model: 'Name',
          label: '任务执行人',
          type: 'input',
          readOnly: true
        },
        {
          model: 'BoatName',
          label: '船舶/车辆',
          type: 'input',
          readOnly: true
        },
        {
          model: 'Elevation',
          label: '高程',
          type: 'input',
          readOnly: true
        },
        {
          model: 'StartTime',
          label: '开始时间',
          type: 'input',
          readOnly: true
        },
        {
          model: 'CompleteTime',
          label: '完成时间',
          type: 'input',
          readOnly: true
        },
        {
          model: 'Location',
          label: '航标设置位置',
          type: 'input',
          readOnly: true
        },
        {
          model: 'UploadLocation',
          label: '实际上传位置',
          type: 'input',
          readOnly: true
        },
        {
          model: 'ReMark',
          label: '备注信息',
          type: 'input',
          readOnly: true
        }
      ],
      operateForm: {
        LaDFM: {},
        LongDFM: {}
      },
      operateRules: {
        AtoNName: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        NavigationType: [
          { required: true, message: '请选择' }
        ],
        ChannelName: [
          { required: true, message: '请选择' }
        ],
        SeaRoute: [
          { required: true, message: '请选择' }
        ],
        AreaName: [
          { required: true, message: '请选择' }
        ],
        Person: [
          { required: true, message: '请选择' }
        ],
        TaskDesc: [
          { required: true, message: '请输入' }
        ],
        Longtitude: [
          { required: true, message: '', validator: this.checkLon }
        ],
        Latitude: [
          { required: true, message: '', validator: this.checkLat }
        ]
      },
      operateFormLabel: [
        {
          model: 'Code',
          label: '编号',
          type: 'input',
          disabled: true
        },
        {
          model: 'AtoNName',
          label: '航标名称',
          type: 'input',
          rule: 'AtoNName'
        },
        {
          model: 'NavigationType',
          label: '航标类型',
          type: 'select',
          opts: [],
          rule: 'NavigationType'
        },
        {
          model: 'ChannelName',
          label: '港口名称',
          type: 'select',
          opts: [],
          rule: 'ChannelName'
        },
        {
          model: 'SeaRoute',
          label: '航道名称',
          type: 'select',
          opts: [],
          rule: 'SeaRoute'
        },
        {
          model: 'AreaName',
          label: '所属海区',
          type: 'select',
          opts: [],
          rule: 'AreaName'
        },
        {
          model: 'Person',
          label: '执行人',
          type: 'select',
          opts: [],
          rule: 'Person'
        },
        {
          model: 'Longtitude',
          label: '经度',
          type: 'longtitude',
          rule: 'Longtitude'
        },
        {
          model: 'Latitude',
          label: '纬度',
          type: 'latitude',
          rule: 'Latitude'
        }
      ]
    }
  },
  created() {
    if (this.tableLabelEx !== 'undefined' && (this.tableLabelEx || []).length > 0) {
      this.tableLabel = this.tableLabelEx
    }
    if (this.operateFormLabelEx !== 'undefined' && (this.operateFormLabelEx || []).length > 0) {
      this.operateFormLabel = this.operateFormLabelEx
    }
    if (this.detailFormLabelEx !== 'undefined' && (this.detailFormLabelEx || []).length > 0) {
      this.detailFormLabel = this.detailFormLabelEx
    }
    console.log('base operateRulesEx:%o', this.operateRulesEx)
    if ((this.operateRulesEx || []).length > 0) {
      console.log('----------rules-----------')
      this.operateRules = this.operateRulesEx
    }
    this.getList()
    this.getNavigationTypeList()
    this.getChannelNameList()
    this.getSeaRouteList()
    this.getUserList()
    this.getAreaNameList()
  },
  methods: {
    disableForm(disabled) {
      this.operateFormLabel.forEach(item => {
        console.log('item:%o', item)
        if (item.model === 'Code') {
          item.disabled = true
        } else if (item.model !== 'Person') {
          item.disabled = disabled
        }
      })
    },
    sure(row) {
      console.log('sure,row:%o', row)
      this.searchResultVisible = false
      this.operateForm = row
      // this.operateForm.Longtitude = dfm2d(row.LongitudeDegree, row.LongitudeMinute, row.LongitudeSecond)
      // this.operateForm.Latitude = dfm2d(row.LatitudeDegree, row.LatitudeMinute, row.LatitudeSecond)

      // this.$set(this.operateForm, 'Longtitude', row.LongitudeDegree + '°' + row.LongitudeMinute + '\'' + row.LongitudeSecond + '\'\'')
      // this.$set(this.operateForm, 'Latitude', row.LatitudeDegree + '°' + row.LatitudeMinute + '\'' + row.LatitudeSecond + '\'\'')
      const lo = { du: row.LongitudeDegree, fen: row.LongitudeMinute, miao: row.LongitudeSecond }
      const la = { du: row.LatitudeDegree, fen: row.LatitudeMinute, miao: row.LatitudeSecond }
      this.$set(this.operateForm, 'LongDFM', lo)
      this.$set(this.operateForm, 'LaDFM', la)
      this.operateForm.Code = 'NG' + getCurrentTime()
      this.disableForm(true)
      this.isShow = true
      this.operateInline = true
    },
    openDetail(row) {
      console.log('openDetail:%o', row)
      this.detailForm = {}
      this.srcList = []
      this.isDetailDrawerShow = true
      // this.detailForm = this.tableData[row.index]
      this.detailForm = JSON.parse(JSON.stringify(this.tableData[row.index]))
      this.detailForm.BeforeLocation = this.detailForm.BeforeLocation.replace('<br>', ' , ')
      this.detailForm.Location = this.detailForm.Location.replace('<br>', ' , ')
      this.detailForm.UploadLocation = this.detailForm.UploadLocation.replace('<br>', ' , ')
      if (this.detailForm.BeforeLocation.indexOf('null') !== -1) {
        this.detailForm.BeforeLocation = '暂未上传'
      }
      if (this.detailForm.UploadLocation.indexOf('null') !== -1) {
        this.detailForm.UploadLocation = '暂未上传'
      }
      if (!isEmpty(row.Files)) {
        this.srcList = row.Files.split(',')
        console.log('----srcs:%o', this.srcList)
      }
    },
    getList() {
      this.config.loading = true
      this.$http
        .get('/task/' + this.reqFuns.getTasks)
        .then(res => {
          this.tableData = res.data.map(item => {
            console.log('item:%o', item)
            let result = ''
            if (this.title === '航标巡检') {
              if (item.Complete === 0) {
                result = ''
              } else {
                result = item.Result === 1 ? '正常' : '异常'
              }
            } else if (this.title === '应急维修') {
              if (item.Complete === 0) {
                result = ''
              } else {
                result = item.Result === 1 ? '完成' : '未完成'
              }
            } else {
              result = item.Result
            }
            return {
              'Code': item.Code,
              'AtoNName': item.AtoNName,
              'NavigationType': item.NavigationType,
              'ChannelName': item.ChannelName,
              'SeaRoute': item.SeaRoute,
              'Location': item.Longtitude + 'E' + '<br\>' + item.Latitude + 'N',
              'BeforeLocation': (item.BeforeLongtitude === null) ? '' : item.BeforeLongtitude + '<br\>' + item.BeforeLatitude,
              'UploadLocation': (item.UploadLatitude === null) ? '' : item.UploadLongtitude + '<br\>' + item.UploadLatitude,
              'Time': item.CompleteTime,
              'Status': item.Complete !== 1 ? '未完成' : '完成',
              'AreaName': item.AreaName,
              'StartTime': item.StartTime,
              'CompleteTime': item.CompleteTime,
              'PublishTime': item.PublishTime,
              'Name': item.name,
              'ReMark': item.ReMark,
              'Files': item.Files,
              'TaskDesc': item.TaskDesc,
              'BoatName': item.BoatName,
              'Elevation': item.Elevation,
              'Result': result
            }
          })
          this.config.total = res.data.count
          console.log('total:' + res.data.count)
          this.config.loading = false
        })
    },
    addTask() {
      this.operateForm = {
        Code: 'NG' + getCurrentTime(),
        LaDFM: {},
        LongDFM: {}
      }
      this.isShow = true
      this.disableForm(false)
    },
    confirm(method) {
      console.log('this.$refs.addForm: %o', this.$refs.addForm)
      console.log('this.$refs.addForm child: %o', this.$refs.addForm.$refs.latitude)
      this.$refs.addForm.$children[0].validate(valid => {
        if (valid) {
          this.$http.post('/task/' + this.reqFuns.addTask, this.operateForm).then(res => {
            console.log(res.data)
            this.isShow = false
            this.getList()
          })
        } else {
          console.log('error add!!')
          return false
        }
      })
    },
    getNavigationTypeList() {
      this.$http.get('/mark/getNavigationTypeList').then(res => {
        res.data.forEach(item => {
          this.operateFormLabel[2].opts.push({ label: item.NavigationType, value: item.NavigationType })
          this.searchBoxData[0].opts.push({ label: item.NavigationType, value: item.NavigationType })
        })
      }).catch(function(err) {
        console.log(err)
      })
    },
    getChannelNameList() {
      this.$http.get('/mark/getChannelNameList').then(res => {
        res.data.forEach(item => {
          this.operateFormLabel[3].opts.push({ label: item.ChannelName, value: item.ChannelName })
          this.searchBoxData[1].opts.push({ label: item.ChannelName, value: item.ChannelName })
        })
      }).catch(function(err) {
        console.log(err)
      })
    },
    getSeaRouteList() {
      this.$http.get('/mark/getSeaRouteList').then(res => {
        res.data.forEach(item => {
          this.operateFormLabel[4].opts.push({ label: item.SeaRoute, value: item.SeaRoute })
          this.searchBoxData[2].opts.push({ label: item.SeaRoute, value: item.SeaRoute })
        })
      }).catch(function(err) {
        console.log(err)
      })
    },
    getAreaNameList() {
      this.$http.get('/mark/getAreaNameList').then(res => {
        res.data.forEach(item => {
          this.operateFormLabel[5].opts.push({ label: item.AreaName, value: item.AreaName })
        })
      }).catch(function(err) {
        console.log(err)
      })
    },
    getUserList() {
      this.$http.get('/user/all').then(res => {
        res.data.forEach(item => {
          var objInForm = this.operateFormLabel.filter(function(i) {
            return i.model === 'Person'
          })
          console.log('objInForm:%o', objInForm)
          objInForm[0].opts.push({ label: item.name, value: item.phoneNumber })
        })
      }).catch(function(err) {
        console.log(err)
      })
    },
    setSearchEvent(data) {
      console.log('search data: %o', data)
      if (Object.keys(data).length === 0) {
        this.$message({
          message: '请设置查询条件！',
          type: 'warning'
        })
        return
      }
      this.$http.post('/mark/search', data).then(res => {
        this.searchResultData = res.data
        this.searchResultVisible = true
      }).catch(function(err) {
        console.log(err)
      })
    },
    delTask(row) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const Code = row.Code
          console.log('Code:' + Code)
          this.$http
            .get('/task/delTask', {
              params: {
                Code
              }
            })
            .then(res => {
              console.log(res.data)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList()
            })
        })
        .catch((err) => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    checkLat(rule, value, callback) {
      const valid = this.$refs.addForm.$refs.latitude[0].validate()
      if (valid) {
        callback()
      } else {
        callback(new Error(' '))
      }
    },
    checkLon(rule, value, callback) {
      const valid = this.$refs.addForm.$refs.longtitude[0].validate()
      if (valid) {
        callback()
      } else {
        callback(new Error(' '))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'src/styles/scss/common';
//.detail_scrollbar{
//  padding-bottom: 16px;
//  max-height: 600px;
//}
</style>
